package com.wgj.android.zfp;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

import com.jiaai.xui.utils.XAppUtils;
import com.jiaai.xui.utils.log.XLog;
import com.wgj.android.R;
import com.wgj.android.http.WeiXinEvents;
import com.wgj.android.http.weixin.WXFormatUtil;
import com.wgj.android.http.weixin.WXHttp;
import com.wgj.android.http.weixin.WeiXinCacheUtil;
import com.wgj.android.http.weixin.model.KeyVal;
import com.wgj.android.http.weixin.model.SyncKey;
import com.wgj.android.http.weixin.model.WXInfo;
import com.wgj.android.ui.activity.CleanFriednsActivity;
import com.wgj.android.ui.activity.WXHongBaoActivity;

import org.greenrobot.eventbus.EventBus;

import java.net.URLEncoder;
import java.util.Date;

/**
 * ========================================
 * 作    者： 佳爱网络有限公司(wwww.jiaailove.com)
 * 版    本： 1.0
 * 创建日期：  2017/11/28
 * 描    述：   微信心跳服务
 * 修订历吏：
 * =========================================
 */
public class WXCheckService extends Service {

    private  static boolean isRun=true;
    private static final String TAG = "微信心跳服务";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new Thread(new CheckLogin()).start();


        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, CleanFriednsActivity.class);
        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
        .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),R.mipmap.logo)) // 设置下拉列表中的图标(大图标)
        .setContentTitle("旺旺通") // 设置下拉列表里的标题
        .setSmallIcon(R.mipmap.logo) // 设置状态栏内的小图标
        .setContentText("旺旺通微信助手") // 设置上下文内容
        .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        startForeground(110, notification);



        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        isRun=false;
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知
        super.onDestroy();

    }

    class  CheckLogin implements Runnable{
        @Override
        public void run() {
            while (isRun){
                    SyncKey syncKey = WeiXinCacheUtil.getSynckey();
                    WXInfo wxInfo = WeiXinCacheUtil.getInfo();
                    if (wxInfo != null && syncKey != null &&  wxInfo.isLogin()){
                        StringBuilder sb = new StringBuilder();
                        for(KeyVal e : syncKey.getList()){
                            if (e.getKey().equals(1)) sb.append("1_").append(e.getVal()).append("%7C");
                            else if (e.getKey().equals(2)) sb.append("2_").append(e.getVal()).append("%7C");
                            else if (e.getKey().equals(3)) sb.append("3_").append(e.getVal()).append("%7C");
                            else if (e.getKey().equals(1000)) sb.append("1000_").append(e.getVal());
                        }
                        String url="";
                        try {
                             url = "http://webpush." + wxInfo.getBaseUrl() + "/cgi-bin/mmwebwx-bin/synccheck?" +
                                    "skey=".concat(URLEncoder.encode(wxInfo.getSkey(), "UTF-8")) +
                                    "&sid=".concat(URLEncoder.encode(wxInfo.getWxsid(), "UTF-8")) +
                                    "&uin=".concat(wxInfo.getWxuin()) +
                                    "&deviceid=".concat("e").concat(WXFormatUtil.getRand15Num()) +
                                    "&_=".concat("" + new Date().getTime()) +
                                    "&synckey=".concat(sb.toString());
                        }catch (Exception e){
                            XLog.e("参数解析错误");
                        }
                        try {
                            String body=WXHttp.obtain().syncGet(url,null);
                            if (body.substring(body.indexOf("retcode:")+8, body.indexOf(",sel")).contains("11")){
                                Log.i(TAG, "微信已退出");
                                wxInfo.setLogin(false);
                                WeiXinCacheUtil.saveInfo(wxInfo);
                                WeiXinCacheUtil.removeCookie();
                                EventBus.getDefault().post(new WeiXinEvents(WeiXinEvents.EventsType.LOGIN_OUT));
                                stopSelf();


                            }else {
                                try {
                                    Log.i(TAG, "成功刷新微信登录"); //todo delete
                                    Thread.sleep(25000);
                                } catch (InterruptedException e) {

                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }

            }
        }



}
